﻿//
//  Monkey Manager
//  Copyright (C) 2012 Victor Tereschenko
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
//     
// ========================================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using ManagerDB;

namespace MonkeyManager.DataProvider
{
    delegate void RequestCompleteDelegate(StoredFile[] files);

    class DelayProvider : IDisposable
    {
        IDatabase mDatabase;
        public DelayProvider(IDatabase database)
        {
            mDatabase = database;
            mThread = new Thread(new ThreadStart(doWork));
            mThread.Start();
        }

        public void Request(Filter filter)
        {
            lock (mFilterLock)
            {
                mFilter = filter;
                mRequestTime = DateTime.Now;
                mEvent.Set();
            }
        }

        void doWork()
        {
            while (true)
            {
                mEvent.WaitOne();
                int timer = 0;
                lock (mFilterLock)
                {
                    if (mFilter == null)
                    {
                        mEvent.Reset();
                        continue;
                    }
                    timer = (DateTime.Now - mRequestTime).Milliseconds;
                }
                while (timer < 250)
                {
                    Thread.Sleep(timer);
                    lock (mFilter)
                        timer = (DateTime.Now - mRequestTime).Milliseconds;
                }
                mEvent.Reset();
                StoredFile[] files = mDatabase.Find(mFilter);
                Callback(files);                
            }
        }

        ManualResetEvent mEvent = new ManualResetEvent(true);
        public event RequestCompleteDelegate Callback;
        Thread mThread;
        Filter mFilter;
        object mFilterLock = new object();
        DateTime mRequestTime;

        bool mDisposing = false;
        public void Dispose()
        {
            if (mDisposing)
                return;
            mDisposing = true;
            mThread.Abort();
        }
    }
}
